import {Component, OnDestroy, OnInit} from '@angular/core';
import {Dialog} from "./dialog";
import {OneDialogService} from "./one-dialog.service";
import {Subscription} from "rxjs/Subscription";

declare var $:any;

@Component({
  selector: 'one-dialog',
  templateUrl: './one-dialog.component.html',
  styleUrls: ['./one-dialog.component.css']
})
export class OneDialogComponent implements OnInit ,OnDestroy{
  private static dialogId ="one-dialog";
  private static modalId = "one-modal";
  dialog:Dialog;
  constructor(
    private oneDialogService : OneDialogService
  ) {
  }

  private subscription : Subscription;
  ngOnInit() {
    this.pull();
  }
  ngOnDestroy(){
    this.subscription.unsubscribe();
  }

  show(){
    if(this.dialog.isModal){
      $('#'+OneDialogComponent.modalId).modal({
        backdrop:'static',
        show:true
      });
    }else {
      $('#'+ OneDialogComponent.dialogId ).show();
    }

  }
  hide(){
    if(this.dialog.isModal){
      $('modal-backdrop').remove();
      $('#'+OneDialogComponent.modalId).modal('hide');
    }else {
      $('#'+ OneDialogComponent.dialogId ).hide();
    }
  }

  pull(){
    this.subscription  = this.oneDialogService.dialogSubject.asObservable()
      .map((dialog:Dialog) => {
        if(!!dialog){
          return dialog.mergeFrom(new Dialog());
        }
      })
      .subscribe(
          (dialog:Dialog) => {
            if(!!dialog){
              this.dialog = dialog.wrap();
              this.show();
            }
          }
        );
    }

    close(){
      this.dialog.closeFun && this.dialog.closeFun();
      this.hide();
    }
    save(){
      this.dialog.okBtnFun && this.dialog.okBtnFun();
      this.hide();
    }
    cancel(){
      this.dialog.cancelBtnFun && this.dialog.cancelBtnFun();
      this.hide();
    }

}
